<?php

require_once 'Operations/Operation.php';

/**
 * Stores a log from the client onto the server.
 */
class UploadFile extends Operation {
	/**
	 * Stores a log from the client onto the server.
	 */
	public function execute() {
		// Get user:
		$userFactory = new UserFactory();
		$user = $userFactory->getCurrent();
		
		// User must be authorized:
		if (!$user->isAuthorized()) {
			throw new PCException("Unauthorized user.", 403);
		}
		
		// Fetch parameters:
		$protocol = HTTPHandler::getHeader("PCProtocol");
		$account = HTTPHandler::getHeader("PCAccount");
		$recipient = HTTPHandler::getHeader("PCRecipient");
		$startDate = HTTPHandler::getHeader("PCStartDate");
		
		// Check input:
		if (!protocol or !$account or !$recipient or !$startDate) {
			throw new PCException("Missing protocol, account, recipient or startDate.", 400);
		}
		
		// Turn into log object:
		$chatlogFactory = new ChatlogFactory();
		$row["protocol"] = $protocol;
		$row["account"] = $account;
		$row["recipient"] = $recipient;
		$row["startDate"] = $startDate;
		$row["contents"] = file_get_contents('php://input');
		$newLog = $chatlogFactory->fromRow($row);
		
		// Fetch existing log:
		$oldLog = ChatlogTable::get($user->getID(), $protocol, $account, $recipient, $startDate);
		if (!$oldLog) {
			// It's a completely new log:
			$log = $newLog;
			$log->setRevision(1);
			
			// Insert the log:
			ChatlogTable::insert($user->getID(), $log);
		} else {
			// Merge the two logs:
			$oldRevision = $oldLog->getRevision();
			if ($oldLog->merge($newLog)) {
				ChatlogTable::update($user->getID(), $oldLog);
			} else {
				// Original log was left unchanged:
				Logger::log("UploadFile", "No need to update original log.");
			}
			
			// Prepare log for display:
			$log = $oldLog;
		}
		
		// Display log as XML:
		HTTPHandler::add($log->toXML());

		// Log activity:
		$logData["protocol"] = $protocol;
		$logData["account"] = $account;
		$logData["recipient"] = $recipient;
		$logData["startDate"] = $startDate;
		$logData["size"] = strlen($row["contents"]);
		if (!$oldLog) {
			$logData["oldRevision"] = 0;
		} else {
			$logData["oldRevision"] = $oldRevision;
		}
		$logData["newRevision"] = $log->getRevision();
		Database::logActivity("UploadFile", $user->getID(), $user->getToken($_SERVER["REMOTE_ADDR"])->getTokenString(), serialize($logData));
	}
}